import myAxios from '../myAxios/myAxios.js';
import myAxios28 from '../myAxios/myAxios28.js';

let GetBuyTypeTable = async function (matcodeInDatabaseList, matcodes) {
	// 创建DataTable的模拟结构（使用数组和对象）
	let table = [];

	// 将逗号分隔的字符串分割为数组[9,11](@ref)
	let matcodeList = matcodes.split(',');

	// 计算分批处理的最大长度和批次数
	let maxLength = 1000;
	let count = Math.ceil(matcodeList.length / maxLength);

	// 使用for循环替代foreach，分批处理物料代码
	for (let i = 0; i < count; i++) {
		let start = maxLength * i;
		let end = (i === count - 1) ? matcodeList.length : start + maxLength;
		let partOfMatcodes = matcodeList.slice(start, end).join(',');
		let TYPE = await myAxios.getSap("SAP根据多物料号查询发货工厂和采购方式", partOfMatcodes + "🈹9900", "9911");
		// console.log('TYPE :>> ', TYPE);
		let result = TYPE.TableSet.O_MATNR;

		let dataRows = result.filter(el => el.BESKZ == 'E' || el.BESKZ == 'X');
		if (dataRows.length > 0) {
			// console.log('dataRows :>> ', dataRows);
			table.push(...dataRows); // 合并行数据
		}
	}

	// 强制添加未在结果中的物料代码
	for (let i = 0; i < matcodeInDatabaseList.length; i++) {
		let matcode = matcodeInDatabaseList[i];
		let matcodeInDt = table.map(row => row.MATNR); // 提取现有MATNR列表
		if (!matcodeInDt.includes(matcode)) {
			table.push({ MATNR: matcode, WERKS: "", BESKZ: "", KDMAT: "", KUNNR: "" });
		}
	}
	console.log('GetBuyTypeTable :>> ', table);
	return table; // 返回模拟的DataTable对象
};


export {
	GetBuyTypeTable
};